package shun.demo.remote.display.server;

import android.os.HandlerThread;
import android.util.Log;
import shun.demo.utils.Singleton;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by chen on 14-4-25.
 */
public class ServerThread extends Thread {

    private HandlerThread mSendThread;
    private SendHandler mSendHandler;
    private Clients mClients;

    public ServerThread() {
        super("Server-SocketAcceptThread");
    }

    @Override
    public void run() {
        // TODO: support stopping the server thread
        mSendThread = new HandlerThread("Server-SendThread");
        mSendThread.start();
        mClients = Singleton.get(Clients.class);
        mSendHandler = new SendHandler(mClients, mSendThread.getLooper());

        try {
            ServerSocket serverSocket = new ServerSocket(Config.PORT, Config.MAX_CLIENTS);
            Log.v(Config.LOG_TAG, "server started");
            while (true) {
                try {
                    Socket socket = serverSocket.accept();
                    // TODO: use session to wrap the socket and receive thread
                    mClients.add(socket);
                    new ReceiveThread(mSendHandler, socket).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
